#include "Character.h"

Character::Character(const std::string& path, int x, int y) : SpriteAnimation(path, x, y), isStomped(false), numContact(0), numLives(5)
{
	spawn.x = x;
	spawn.y = y;
}

Character::~Character()
{
}

void Character::OnCollisionEnter(b2Fixture* fixture)
{
	switch (fixture->GetFilterData().categoryBits)
	{
		case CollisionCategories::WORLD_CATEGORY: {
			numContact++;
		} break;

		case CollisionCategories::PLAYER_UPPER_CATEGORY: {
			Audio::GetInstance()->PlaySound("stomp.wav", 100);
			isStomped = true;
		} break;

		default:
		{
		} break;
	}
}

void Character::OnCollisionLeave(b2Fixture* fixture)
{
	switch (fixture->GetFilterData().categoryBits)
	{
		case CollisionCategories::WORLD_CATEGORY: {
			numContact--;
		} break;

		default:
		{
		} break;
	}
}

void Character::Update(unsigned int t)
{
	if (body->GetLinearVelocity().x > 0.0f)
	{
		SetCurrentDirection(RIGHT);
		SetNumberOfFrame(2);
	}
	if (body->GetLinearVelocity().x < 0.0f)
	{
		SetCurrentDirection(LEFT);
		SetNumberOfFrame(2);
	}
	else if (body->GetLinearVelocity().x == 0.0f)
	{
		SetNumberOfFrame(1);
	}

	SpriteAnimation::Update(t);
}

void Character::Move(float deltaX)
{
	b2Vec2 current;
	current.x = body->GetLinearVelocity().x;
	current.y = body->GetLinearVelocity().y;
	if (glm::abs(current.x) < 40.f)
	{
		current.x += deltaX;
	}

	current.x *= 0.9f;

	body->SetLinearVelocity(current);
}

void Character::Jump()
{
	if (isTouchingGround())
	{
		b2Vec2 current;
		current.x = body->GetLinearVelocity().x;
		current.y = body->GetLinearVelocity().y;
		current.y += -100.f;

		float panning = body->GetPosition().x / (DEFAULT_WIN_W * 0.5f);
		Audio::GetInstance()->PlaySound("jump.wav", 100, panning);
		body->SetLinearVelocity(current);
	}
}

void Character::Respawn()
{
	body->SetTransform(spawn, 0.f);
	body->SetLinearVelocity(b2Vec2_zero);
	isStomped = false;
	numLives--;
}

void Character::Reset()
{
	Respawn();
	numLives = 5;
}

bool Character::isTouchingGround()
{
	return glm::abs(body->GetLinearVelocity().y) < 1.0f &&
		numContact != 0;
}